package IU;

import Controladores.CtrlUsuario;
import Entidades.Operariorol;
import Entidades.Usuario;
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class Iniciar extends javax.swing.JFrame {

    private JFrame controllingFrame; //needed for dialogs
    private static Operariorol p;//Persona p;
    private static Usuario u;//Persona p;
    private static String nombr;
    private static int rol;
    private static int cargo;
    private static int area;
    //private static char[] contras;
    private static String contrasenia;
    private List<Usuario> listaUsuario = new ArrayList<Usuario>();
//    InputMap map = new InputMap();


    /** Creates new form Iniciar */
    public Iniciar() {
        initComponents();
        PanelFondo F = new PanelFondo();

//        jPasswordField1.addKeyListener(new PresionarTecla());

        this.add(F, BorderLayout.CENTER);
        this.pack();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        nombre = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu2 = new javax.swing.JMenu();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Ingreso al Sistema");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED), "Registro ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 3, 14), new java.awt.Color(102, 0, 102))); // NOI18N

        nombre.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jLabel7.setFont(new java.awt.Font("Segoe UI", 1, 12));
        jLabel7.setForeground(new java.awt.Color(102, 0, 102));
        jLabel7.setText("Usuario:");

        jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 12));
        jLabel3.setForeground(new java.awt.Color(102, 0, 102));
        jLabel3.setText("Contraseña:");

        jPasswordField1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPasswordField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordField1ActionPerformed(evt);
            }
        });

        jLabel2.setForeground(new java.awt.Color(204, 0, 0));
        jLabel2.setText("* Olvide Usuario o Contraseña - Solicitarlo en Inicio Ayuda");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel1)
                        .add(18, 18, 18)
                        .add(jLabel4)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 177, Short.MAX_VALUE))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .add(91, 91, 91)
                        .add(jLabel5)
                        .add(14, 14, 14)))
                .add(240, 240, 240))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(449, Short.MAX_VALUE)
                .add(jLabel6)
                .addContainerGap())
            .add(jPanel1Layout.createSequentialGroup()
                .add(49, 49, 49)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel2)
                    .add(jLabel3)
                    .add(jLabel7)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(92, 92, 92)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jPasswordField1)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, nombre, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE))))
                .addContainerGap(132, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(10, 10, 10)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel4)
                            .add(jLabel5))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(nombre, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel7))
                        .add(28, 28, 28)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jPasswordField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel3))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 37, Short.MAX_VALUE)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jLabel6)
                            .add(jLabel2)))
                    .add(jLabel1)))
        );

        jButton1.setFont(new java.awt.Font("Segoe UI", 3, 12));
        jButton1.setForeground(new java.awt.Color(102, 0, 102));
        jButton1.setText("Ingresar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel8.setBackground(new java.awt.Color(153, 153, 153));
        jLabel8.setFont(new java.awt.Font("Segoe UI", 3, 48));
        jLabel8.setForeground(new java.awt.Color(93, 47, 93));
        jLabel8.setText("Gestor Pesaje");

        jMenu2.setForeground(new java.awt.Color(102, 0, 102));
        jMenu2.setText("Inicio");
        jMenu2.setFont(new java.awt.Font("Segoe UI", 1, 12));

        jMenu1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImagenFondo/iconoPesaje1.jpg"))); // NOI18N
        jMenu1.setText("Usuario y Contraseña");

        jMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/contrasena.jpg"))); // NOI18N
        jMenuItem2.setText("Cambiar Usuario / Contraseña");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);
        jMenu1.add(jSeparator1);

        jCheckBoxMenuItem1.setText("Recuperar Usuario / Contraseña");
        jCheckBoxMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/contrasena.jpg"))); // NOI18N
        jCheckBoxMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jCheckBoxMenuItem1);

        jMenu2.add(jMenu1);

        jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/return.gif"))); // NOI18N
        jMenuItem1.setText("Salir");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem1);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap(648, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jLabel8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 315, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(78, 78, 78))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(29, 29, 29))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 117, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(206, 206, 206))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(41, 41, 41)
                .add(jButton1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 97, Short.MAX_VALUE)
                .add(jLabel8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 77, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(41, 41, 41))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
CambioClave cambioclave = new CambioClave();
cambioclave.setVisible(true);// TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        ingresarPassName();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jPasswordField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordField1ActionPerformed

    private void jCheckBoxMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuItem1ActionPerformed
RecuperarUC ruc = new RecuperarUC();
ruc.setVisible(true);// TODO add your handling code here:
    }//GEN-LAST:event_jCheckBoxMenuItem1ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1ActionPerformed
    /**
     * @param args the command line arguments
     */
    /*public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    Iniciar p = new Iniciar();
    p.setLocationRelativeTo(null);
    p.setVisible(true);
    }
    });
    }

    si no funciona el main de arriba usar este
//     */
//    public class PresionarTecla extends KeyAdapter {
//
//      public void keyPressed(KeyEvent ke) {
//          if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
//              jPasswordField1ActionPerformed(null);
//          }
//      }
//}
    public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlueIceLookAndFeel");
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Iniciar p = new Iniciar();
                p.setLocationRelativeTo(null);
                p.setVisible(true);


            }
        });


    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JTextField nombre;
    // End of variables declaration//GEN-END:variables

    private void limpiarCampos() {
        nombre.setText("");
        jPasswordField1.setText("");

    }

    public String encriptar(String info_a_encriptar) {

        String abc1 = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ";
        //Variable que contendrá la información encriptada
        String info_encriptada = "";
        //variable
        Boolean cambio = false;
        //Bucle for mientras i sea menor al largo de la cadena a encriptar
        for (int i = 0; i < info_a_encriptar.length(); i++) {
            //Bucle mientras j sea menor al patron impuesto en la variable abc1
            for (int j = 0; j < abc1.length(); j++) {
                //Si la letra es igual a una de las letras del patrón.
                if (info_a_encriptar.charAt(i) == abc1.charAt(j)) {
                    //Cambiamos a true la variable boolean
                    cambio = true;
                    //Condicionales para no pasarse del total de letras del patrón.
                    if ((j == 24) || (j == 25) || (j == 26) || (j == 51) || (j == 52) || (j == 53)) {
                        //si el indice j es igual a estos límites
                        //Asignamos encriptando esta letra el valor del array abc1 de j menos 24
                        info_encriptada = info_encriptada + abc1.charAt(j - 24);
                    } else {
                        //Sino fuera así le asignamos el valor del array abc1 de j mas 3
                        info_encriptada = info_encriptada + abc1.charAt(j + 3);
                    }
                    //El valor de j lo ponemos a 53 y terminamos el bucle for
                    j = 53;
                }
            }
            //Si cambio es igual a false
            if (!cambio) {
                //Cargamos en la variable que contendrá el resultado el valor del caracter
                //de la info a encriptar
                info_encriptada = info_encriptada + info_a_encriptar.charAt(i);
            }
            //Damos a la variable boolean el valor false
            cambio = false;
        }
        //Si se termino de recorrer la palabra, frase o archivo enviado...
        //Damos a la variable original enviada a la función el valor de la variable
        //que contiene la encriptación.
        info_a_encriptar = info_encriptada;
        //Retornamos dicho valor.
        return info_a_encriptar;
    }

    private void ingresarPassName() {
        CtrlUsuario controlUsuario = new CtrlUsuario();
        String pass = encriptar(jPasswordField1.getText());
        String name = nombre.getText();
        boolean verificar = controlUsuario.verificarUsuarioContrasenia(pass, name);
        //Controlador con = new Controlador();
//        CtrlUsuario con = new CtrlUsuario();
//        //Iterator us = null;
//        try {
//            //us = (Iterator) con.buscarTodosUsuario(); //buscarUsuario();
//            listaUsuario = con.buscarTodosUsuario();
//        } catch (Exception ex) {
//            Logger.getLogger(Iniciar.class.getName()).log(Level.SEVERE, null, ex);
//            System.out.println("excepcion al recuperar todos los usuarios" + ex);
//        }
//        nombr = nombre.getText();
//        contrasenia = jPasswordField1.getText();
//        //contras = jPasswordField1.getPassword();
//        if(listaUsuario != null){
//            System.out.println("Tamaño de lista usuarios " + listaUsuario.size());
//            boolean usuarioEncontrado = false;
//            for (int i = 0; i < listaUsuario.size(); i++) {
//                Usuario user = (Usuario) listaUsuario.get(i);
//                p = (Operariorol) listaUsuario.get(i).getOperariorol();
//                rol = p.getRol().getIdRol();
//                cargo = p.getCargo().getIdCargo();
//                area = p.getArea().getIdArea();
//               String u =user.getNombre();
//               String op = p.getOperario().getApellido();
//                if(user.getNombre().equals(nombr)){//getNombrePersona()// if(u.getusuario_contrasenia().equals(contrasenia)){
//                    usuarioEncontrado = true;
//                    System.out.println("el nom: " + user.getNombre());//System.out.println("el nom" +p.getNombrePersona());
//                    Principal principal = new Principal(rol,cargo,area,u,op);
//                    principal.setLocationRelativeTo(null);
//                    principal.setVisible(true);
//                    hide();
//                }
//            }
        if (!verificar) {
            JOptionPane.showMessageDialog(this, "\nUsuario/contraseña incorrecto.\n ", "Iniciar sesión", JOptionPane.ERROR_MESSAGE);
        } else {
            Usuario usuario = controlUsuario.buscarUsuario(pass, name);
            Principal principal = new Principal(usuario.getOperariorol().getRol().getIdRol(), usuario.getOperariorol().getCargo().getIdCargo(), usuario.getOperariorol().getArea().getIdArea(), name, usuario.getOperariorol().getOperario().getApellido());
            principal.setLocationRelativeTo(null);
            principal.setVisible(true);
            hide();
            // JOptionPane.showMessageDialog(this, "\nNo existen usuarios.\n ", "Iniciar sesión", JOptionPane.WARNING_MESSAGE);
        }

        limpiarCampos();
        // }
        // TODO add your handling code here:
    }
}
